package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect //切片类
@Component
public class AutoFillAspect {

    @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        log.info("进入AOP程序，为公共属性复制");

        //1.获取原始方法时传入的参数，获取第一个（对象）
        Object[] args = joinPoint.getArgs();
        if(ObjectUtils.isEmpty(args)){    //判断参数是否为空
            return;
        }

        Object obj = args[0];

        //2.通过反射获取到对象对应的方法（4个）
        Method setCreateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
        Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME , LocalDateTime.class);
        Method setCreateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
        Method setUpdateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

        //3.获取对应的value属性
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class); //获取原方法上的注解
        OperationType operationType = autoFill.value(); //获取注解的value属性

        //4.判断，如果是insert，为4个属性赋值
        if(operationType.equals(OperationType.INSERT)){
            setCreateTime.invoke(obj, LocalDateTime.now());
            setCreateUser.invoke(obj, BaseContext.getCurrentId());
        }

        setUpdateTime.invoke(obj, LocalDateTime.now());
        setUpdateUser.invoke(obj, BaseContext.getCurrentId());

        //5.判断，是update，为2个属性赋值
    }
}
